//
//  RootViewController.m
//  UI9_UITableView编辑HW
//
//  Created by dllo on 15/11/19.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import "Student.h"
#import "DetailViewController.h"
#import "AddViewController.h"

@interface RootViewController ()<UITableViewDataSource, UITableViewDelegate, AddViewControllerDelegate>

@property (nonatomic, retain) NSMutableDictionary *stuDic;
@property (nonatomic, retain) UITableView *tableV;
//@property (nonatomic, retain) NSArray *tempArr;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"通讯录";
    
    [self getDate];
 
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(leftAction:)] autorelease];
    


    
    
}

// 监测移动过程, 实现限制跨区移动
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{

    if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
        return sourceIndexPath;
    } else {
        return proposedDestinationIndexPath;
    }

}




// 移动完成
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{

    NSString *key = [self.stuDic.allKeys objectAtIndex:sourceIndexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    
    // 根据源地址找到待操作的学生对象
    // 注意, 手动进行引用计数加1操作, 防止从数组移除后因为计数减1引起空间释放
    Student *stu = [[arr objectAtIndex:sourceIndexPath.row] retain];
    [arr removeObjectAtIndex:sourceIndexPath.row];
    
    
    // 找到移动的目的地
    NSString *desKey = [self.stuDic.allKeys objectAtIndex:destinationIndexPath.section];
    NSMutableArray *desArr = [self.stuDic objectForKey:desKey];
    
    [desArr insertObject:stu atIndex:destinationIndexPath.row];
    
    [stu release];
    
    [self.tableV reloadData];
    
}




// 返回可以移动的
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 添加界面delegate的实现方法
- (void)addToStuDic:(Student *)stu
{
    if (stu.name.length != 0) {
          NSString *key = [stu.name substringToIndex:1];
        NSMutableArray *arr = nil;
        if ([self.stuDic objectForKey:key] != nil) {
            arr = [self.stuDic objectForKey:key];
            [arr addObject:stu];
            
            
        } else {
            arr = [NSMutableArray array];
            [arr addObject:stu];
            [self.stuDic setObject:arr forKey:key];
            
        }
    }
    
    [self.tableV reloadData];

}
// 左上角按钮点击跳转到添加界面
- (void)leftAction:(UIBarButtonItem *)sender
{
    AddViewController *addVC = [[AddViewController alloc] init];
//    [self presentViewController:addVC animated:YES completion:^{
//        
//        
//    }];
//    [addVC release];
    addVC.delegate = self;
    [self.navigationController pushViewController:addVC animated:YES];
}
// 使处于可编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableV setEditing:editing animated:animated];
}
// 返回可以编辑的
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
// 编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
//    if (indexPath.section < 2) {
//        return UITableViewCellEditingStyleInsert;
//    } else {
//        return UITableViewCellEditingStyleDelete;
//    }
}
// 编辑完成
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [self.stuDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        [arr removeObjectAtIndex:indexPath.row];
        if (arr.count == 0) {
            [self.stuDic removeObjectForKey:key];
        }
        
//        [self.tableV deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
        [self.tableV reloadData];
    }
  
}



- (void)getDate
{
    //解析路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HW" ofType:@"plist"];
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    self.stuDic = [NSMutableDictionary dictionary];
    
    for (NSString *key in dic) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *tempDic in [dic objectForKey:key]) {
            Student *stu = [[Student alloc] init];
            stu.name = [tempDic objectForKey:@"name"];
            stu.phone = [tempDic objectForKey:@"phone"];
            stu.sex = [tempDic objectForKey:@"sex"];
            stu.age = [tempDic objectForKey:@"age"];
            stu.image = [tempDic objectForKey:@"image"];
            
            [arr addObject:stu];
            [stu release];
        }
        [self.stuDic setObject:arr forKey:key];
    }
    // 排序
//    self.tempArr = [self.stuDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
}
// 选中行触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    
    NSString *key = [self.stuDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    Student *stu = [arr objectAtIndex:indexPath.row];
    detailVC.stu = stu;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}
// 右侧
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.stuDic.allKeys;
}
// 区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.stuDic.allKeys objectAtIndex:section];
}
// 区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.stuDic.allKeys.count;
}
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [self.stuDic.allKeys objectAtIndex:section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    return arr.count;
}
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr] autorelease];
        
    }
    NSString *key = [self.stuDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    Student *stu = [arr objectAtIndex:indexPath.row];
    
    cell.textLabel.text = stu.name;
    cell.detailTextLabel.text = stu.phone;
    cell.imageView.image = [UIImage imageNamed:stu.image];
    return cell;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
